<?php
abstract class Model
{
    /**
     * @var Database null
     */
    protected $_db = null;

    public function __construct()
    {
        $this->_db = Loader::getInstance()->database();
    }

    /**
     * Insert into table
     * @param $tableName
     * @param array $data
     * @return int new inserted id
     */
    protected function _insert($tableName, array $data)
    {
        $data = $this->cleanData($data);

        $query = "
            INSERT INTO $tableName (". implode(",", array_keys($data)) .")
            VALUES (". implode(",", $data) .")
        ";

        $this->_db->query($query);

        return $this->_db->getInsertId();
    }

    protected function _update($tableName, array $data, $idField)
    {
        var_dump($data);
        // prepare the primary field
        $idField = $this->_db->escape($idField);
        $idValue = intval($data[$idField]);

        $data = $this->cleanData($data);

        // create updating field string
        $updatingFields = array();
        foreach ($data as $field => $value)
        {
            // ignore the primary field
            if ($field == $idField)
            {
                continue;
            }

            $updatingFields[] = $field . ' = ' . $value;
        }
        $updatingFields = implode(', ', $updatingFields);

        $query = "
            UPDATE $tableName SET $updatingFields WHERE $idField = $idValue
        ";

        return $this->_db->query($query);
    }

    protected function _delete($tableName, $idField, $idValue)
    {
        $tableName = $this->_db->escape($tableName);
        $idField = $this->_db->escape($idField);
        $idValue = $this->_db->escape($idValue);

        return $this->_db->query("DELETE FROM $tableName WHERE $idField = $idValue");
    }

    /**
     * Hm, just push the value into two quotes
     * @param array $data
     * @return string
     */
    public function cleanData(array $data)
    {
        foreach ($data as $field => $value)
        {
            $data[$field] = "'" . $this->_db->escape($value) . "'";
        }

        return $data;
    }
}